<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>

          <a-col :md='6' :sm='12'>
            <a-form-item label='货品名称'>
              <a-input placeholder='请输入货品名称查询' v-model='queryParam.name'></a-input>
            </a-form-item>
          </a-col>

          <a-col :md='6' :sm='12'>
            <a-form-item label='货物编号'>
              <a-input placeholder='请输入货物编号查询' v-model='queryParam.partNo'></a-input>
            </a-form-item>
          </a-col>

          <a-col :md='6' :sm='12'>
            <a-form-item label='外部编号'>
              <a-input placeholder='请输入外部编号查询' v-model='queryParam.outNo'></a-input>
            </a-form-item>
          </a-col>

          <a-col :md='6' :sm='12'>
            <a-form-item label='主机厂项目'>
              <a-select
                mode='multiple'
                style='width: 100%'
                :getPopupContainer='(target) => target.parentNode'
                placeholder='请选择主机厂项目'
                optionFilterProp='children'
                v-model='selectOptions.selectedMainEngine'>
                <a-select-option v-for='(e,i) in mainEngineDictList' :key='i.toString()' :value='e.mainEngineNo'>
                  {{ e.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <template v-if='toggleSearchStatus'>
            <a-col :md='6' :sm='12'>
              <a-form-item label='货品类型'>
                <a-select
                  mode='multiple'
                  style='width: 100%'
                  :getPopupContainer='(target) => target.parentNode'
                  placeholder='请选择货品类型'
                  optionFilterProp='children'
                  v-model='selectOptions.selectedPartType'>
                  <a-select-option v-for='(e,i) in partTypeDictList' :key='i.toString()' :value='e.partType'>
                    {{ e.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md='6' :sm='12'>
              <a-form-item label='应用车型'>

                <a-select
                  mode='multiple'
                  style='width: 100%'
                  :getPopupContainer='(target) => target.parentNode'
                  placeholder='请选择应用车型'
                  optionFilterProp='children'
                  v-model='selectOptions.selectedMotorType'>
                  <a-select-option v-for='(e,i) in applicationMotorModelDictList' :key='i.toString()'
                                   :value='e.motorType'>
                    {{ e.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>


          <a-col :md='6' :sm='8'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='searchQuery' icon='search'>查询</a-button>
              <a-button type='primary' @click='searchReset' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class='table-operator' style='border-top: 5px'>
      <a-button @click='handleAdd' type='primary' icon='plus'>添加货品信息</a-button>
      <a-upload
        name='file'
        :multiple='true'
        action='/api/motorfactory/motor-part/importMotorPartExcel'
        :headers='headers'
        :show-upload-list='false'
        @change='handleChange'
      >
        <a-button type='primary'>
          <a-icon type='upload' />
          导入货品
        </a-button>
      </a-upload>
      <a-button type='primary' icon='download' :loading='downloadLoading' @click='downloadTemplate()'>下载货品模板</a-button>
      <a-button type='primary' icon='download' :loading='downloadLoading' @click="handleExportXls('货品信息')">导出货品
      </a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay' @click='handleMenuClick'>
          <a-menu-item key='1'>
            <a-icon type='delete' @click='batchDel' />
            删除
          </a-menu-item>

        </a-menu>
        <a-button style='margin-left: 8px'>
          批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i>已选择&nbsp;<a style='font-weight: 600'>{{
          selectedRowKeys.length
        }}</a>项&nbsp;&nbsp;
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        bordered
        size='middle'
        rowKey='id'
        :scroll='{ x: 3000 }'
        :columns='columns'
        :dataSource='dataSource'
        :pagination='ipagination'
        :loading='loading'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='handleTableChange'>

        <span slot='tags' slot-scope='text, record'>
                 <a-tag
                   v-for='item in JSON.parse(JSON.stringify(text))'
                   :key='item.id'
                   color='geekblue'
                 >
                {{ handlerTags(item) }}
              </a-tag>
        </span>

        <span slot='filePreview' slot-scope='text, record'>
                 <a-button
                   type='primary'
                   @click='previewAtta(record)'
                 >
                预览附件
              </a-button>
        </span>

        <span slot='specifications' slot-scope='text, record'>
             <a-tag
               color='purple'
             >
                {{ text === '1' ? '件' : '个' }}
              </a-tag>
        </span>

        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>编辑</a>

          <a-divider type='vertical' />

           <a @click="handleWarehouse('in',record)">入库</a>

          <a-divider type='vertical' />

           <a @click="handleWarehouse('out',record)">出库</a>

          <a-divider type='vertical' />

          <a-dropdown>
            <a class='ant-dropdown-link'>
              更多 <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->


    <motor-part-model ref='modalForm' @ok='modalFormOk'></motor-part-model>

    <warehouse-model ref='warehouseForm' @ok='modalFormOk'></warehouse-model>

    <atta-image-model ref='previewImageModal'></atta-image-model>


  </a-card>
</template>

<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { ListMixin } from '@/mixins/ListMixin'
import MotorPartModel from './modules/MotorPartModel'
import WarehouseModel from './modules/WarehouseModel'
import AttaImageModel from './modules/AttaImageModel'

import { getApplicationMotorModelDict, getMainEngineRelsDict, getPartTypeDict, downloadPartTemplate } from '@/api/api'

export default {
  name: 'MotorPartList',
  mixins: [ListMixin],
  components: {
    MotorPartModel,
    WarehouseModel,
    AttaImageModel
  },
  data() {
    return {
      headers: {},
      description: '货品管理页面',
      queryParam: {},
      partTypeDict: new Map(),
      applicationMotorModelDict: new Map(),
      mainEngineDict: new Map(),
      partTypeDictList: [],
      applicationMotorModelDictList: [],
      mainEngineDictList: [],
      selectOptions: {
        selectedMainEngine: [],
        selectedPartType: [],
        selectedMotorType: []
      },
      recycleBinVisible: false,
      columns: [
        {
          title: '货品名称',
          align: 'center',
          dataIndex: 'name',
          sorter: false,
          width: 200,
          fixed: true
        },
        {
          title: '货品编号',
          align: 'center',
          dataIndex: 'partNo',
          width: 200,
          sorter: false
        },
        {
          title: '外部编号',
          align: 'center',
          dataIndex: 'outNo',
          width: 200,
          sorter: false
        },
        {
          title: '录入时间',
          align: 'center',
          dataIndex: 'createTime',
          width: 200,
          sorter: true
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'specifications',
          sorter: false,
          scopedSlots: { customRender: 'specifications' }
        },
        {
          title: '产品描述',
          align: 'center',
          dataIndex: 'description',
          ellipsis: true,
          sorter: false
        },
        {
          title: '库存数量',
          align: 'center',
          dataIndex: 'storeSum',
          sorter: true
        },
        {
          title: '责任人',
          align: 'center',
          dataIndex: 'principalName',
          sorter: false
        },
        {
          title: '附件信息',
          align: 'center',
          dataIndex: 'attaIds',
          ellipsis: true,
          sorter: false,
          scopedSlots: { customRender: 'filePreview' }
        },
        {
          title: '主机厂项目',
          align: 'left',
          dataIndex: 'partMainEngineRels',
          width: 600,
          ellipsis: true,
          scopedSlots: { customRender: 'tags' },
          sorter: false
        },
        {
          title: '应用车型',
          align: 'left',
          dataIndex: 'partApplicationMotorModelRels',
          width: 400,
          ellipsis: true,
          scopedSlots: { customRender: 'tags' },
          sorter: false
        },
        {
          title: '货品类型',
          align: 'left',
          dataIndex: 'partAndTypeRels',
          ellipsis: true,
          scopedSlots: { customRender: 'tags' },
          width: 400,
          sorter: false
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          fixed: 'right',
          width: 200
        }
      ],
      url: {
        list: '/motorfactory/motor-part/list',
        delete: '/motorfactory/motor-part/delete',
        deleteBatch: '/motorfactory/motor-part/deleteBatch',
        exportXlsUrl: '/motorfactory/motor-part/exportXls'
      },
      warehouseForm: {}
    }
  },
  computed: {},
  watch: {
    selectOptions: {
      handler(newVal, oldVal) {
        if (this.selectOptions.selectedMainEngine) this.queryParam.selectedMainEngine = this.selectOptions.selectedMainEngine.join(',')
        if (this.selectOptions.selectedPartType) this.queryParam.selectedPartType = this.selectOptions.selectedPartType.join(',')
        if (this.selectOptions.selectedMotorType) this.queryParam.selectedMotorType = this.selectOptions.selectedMotorType.join(',')
      },
      deep: true,
      immediate: true
    },
    queryParam: {
      handler(newVal, oldVal) {
        if (!this.queryParam.selectedMainEngine) this.selectOptions.selectedMainEngine = []
        if (!this.queryParam.selectedPartType) this.selectOptions.selectedPartType = []
        if (!this.queryParam.selectedMotorType) this.selectOptions.selectedMotorType = []
      },
      deep: true,
      immediate: true
    }

  },
  methods: {
    downloadTemplate() {
      // 下载货品excel模板
      downloadPartTemplate().then((res) => {
        const blob = new Blob([res])
        let fileName = '货品清单模板.xlsx'
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click()// 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else {// 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleChange(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 导入成功`)
        this.searchReset()

      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 导入失败.`)
      }
    },
    handleWarehouse(tag, record) {
      console.log(tag, record)
      if (tag === 'in') {
        this.$refs.warehouseForm.isWarehouseIn = true
        this.$refs.warehouseForm.edit(record)
        this.$refs.warehouseForm.title = '入库操作【货品：  ' + record.name + '  |  编号： ' + record.partNo + '】'
        this.$refs.warehouseForm.disableSubmit = false
      } else if (tag === 'out') {
        this.$refs.warehouseForm.isWarehouseIn = false
        this.$refs.warehouseForm.edit(record)
        this.$refs.warehouseForm.title = '出库操作【货品：  ' + record.name + '  |  编号： ' + record.partNo + '】'
        this.$refs.warehouseForm.disableSubmit = false
      }

    },
    handleMenuClick(e) {
      if (e.key == 1) {
        this.batchDel()
      } else if (e.key == 2) {
        this.batchFrozen(2)
      } else if (e.key == 3) {
        this.batchFrozen(1)
      }
    },
    initialDictMap() {
      let _that = this
      getApplicationMotorModelDict().then((res) => {
        this.$nextTick(() => {
          _that.applicationMotorModelDict = _that.hadlerDicts(res.result)
          _that.applicationMotorModelDictList = res.result
        })
      })
      getPartTypeDict().then((res) => {
        this.$nextTick(() => {
          _that.partTypeDict = _that.hadlerDicts(res.result)
          _that.partTypeDictList = res.result
        })

      })
      getMainEngineRelsDict().then((res) => {
        this.$nextTick(() => {
          _that.mainEngineDict = _that.hadlerDicts(res.result)
          _that.mainEngineDictList = res.result
        })

      })
      console.log('init dict complete')
    },
    hadlerDicts(dicts) {
      let dictMap = new Map()
      if (dicts) {
        for (let dict of dicts) {
          if (dict.motorType) {
            dictMap.set(dict.motorType, dict.name)
          } else if (dict.mainEngineNo) {
            dictMap.set(dict.mainEngineNo, dict.name)
          } else if (dict.partType) {
            dictMap.set(dict.partType, dict.name)
          }
        }
        return dictMap
      }
    },
    handlerTags(item) {
      let applicationMotorModelDict = this.applicationMotorModelDict
      let mainEngineDict = this.mainEngineDict
      let partTypeDict = this.partTypeDict
      if (item.motorType !== undefined && applicationMotorModelDict !== undefined) {
        return applicationMotorModelDict.get(item.motorType)
      }
      if (item.mainEngineNo !== undefined && mainEngineDict !== undefined) {
        return mainEngineDict.get(item.mainEngineNo)
      }
      if (item.partType !== undefined && partTypeDict !== undefined) {
        return partTypeDict.get(item.partType)
      }
    },
    previewAtta(record) {
      this.$refs.previewImageModal.showModal(record)
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }

    this.initialDictMap()
  }

}
</script>